package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.business.service.LoginService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AliEftOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();


    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("eft订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo query = new TOrderInfo();
        query.setChannelType("alipay");
        query.setChannel("alipay_eft_h5");
        query.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(query);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        for (TOrderInfo orderInfo : orderInfos) {
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://mposapi.bjmymf.com/api/Pay/GetPayOrder";
            String cookieStr = userRecipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String token = cookieObj.getString("token");

            JSONObject queryObj = new JSONObject();
            queryObj.put("txType", 0);
            queryObj.put("pageNum", 1);
            queryObj.put("status", 1);
            queryObj.put("pageSize", 10);
            queryObj.put("starTime", startTimeStr);
            queryObj.put("maxMoney", -1);
            queryObj.put("minMoney", -1);
            queryObj.put("type", 1);
            queryObj.put("endTime", endTimeStr);
            queryObj.put("startID", "");
            HashMap<String, String> headerMap = new HashMap();
            headerMap.put("Token", token);
            headerMap.put("Ver", "1.2.1");
            headerMap.put("User-Agent", "CXZY/1.2.1 (iPhone; iOS 15.4.1; Scale/3.00)");
            headerMap.put("AppSource", "iOS");
//            logger.info("eft订单查询请求：" + queryObj.toJSONString());
            String httpResponse = HttpUtils.sendJsonMessage(url, headerMap, queryObj.toJSONString());
            JSONObject resultObj = JSONObject.parseObject(httpResponse);
//            logger.info("eft订单查询.." + resultObj);
            int resultCode = resultObj.getInteger("code");
            if (resultCode == 0 ) {
                int total = resultObj.getInteger("total");
                if(total > 0) {
                    JSONArray recordList = resultObj.getJSONArray("rows").getJSONObject(0).getJSONArray("detailList");
                    for (int i = 0; i < recordList.size(); i++) {
                        JSONObject recordObj = recordList.getJSONObject(i);
                        if (recordObj.getString("payType").equals("1") && recordObj.getString("status").equals("1") && orderInfo.getRealMoney().equals(recordObj.getLong("money"))) {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String insertDateStr = recordObj.getString("insertDate");
                            logger.info("insertDateStr.." + insertDateStr);

                            Date createTime = orderInfo.getCreateTime();
                            Date validTime = orderInfo.getValidTime();
                            Date insertDate = dateFormat.parse(insertDateStr);
                            logger.info("eft订单创建时间.." + dateFormat.format(createTime));
                            //订单创建时间往前移5秒
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(createTime);
                            calendar.add(Calendar.SECOND, -5);
                            String dateCreateStr  = dateFormat.format(calendar.getTime());
                            createTime = dateFormat.parse(dateCreateStr);
                            logger.info("eft前移5秒后的订单创建时间.." + dateFormat.format(createTime));
                            logger.info("eft订单失效时间.." + dateFormat.format(validTime));
                            logger.info("eft订单回调时间.." + dateFormat.format(insertDate));
                            //insertDate  判断账单时间大于订单生成时间
                            int k = insertDate.compareTo(createTime);
                            //insertDate  判断账单时间小于订单失效时间
                            int k1 = insertDate.compareTo(validTime);
                            logger.info("eft订单回调时间是否大于创建时间：" + k);
                            logger.info("eft订单回调时间是否小于失效时间：" + k1);
                            if (k > 0 && k1 < 0) {
                                logger.info("eft订单查询.." + recordObj);
                                MsgPayResult msgPayResult = new MsgPayResult();
                                msgPayResult.setChannel(orderInfo.getChannel());
                                msgPayResult.setTradeNo(orderInfo.getId().toString());
                                msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                                msgPayResult.setOrderId(recordObj.getString("payorderID"));
                                msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getRealMoney() + ""));
                                msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                                msgPayResult.setBillTime(recordObj.getString("insertDate"));

                                msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                                chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                                chargeService.notifyUserPaySucc(orderInfo.getId());
                                logger.info("eft订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getRealMoney());
                                //休息5秒后回调成功后查询是否结算到银行卡
//                                logger.info("eft查询到账时间.." + dateFormat.format(new Date()));
//                                Thread.sleep(3*1000);
//                                logger.info("延迟3秒后eft查询到账时间.." + dateFormat.format(new Date()));
//                                String bankAccountLogID = recordObj.getString("bankAccountLogID");
//                                JSONObject bankDfObj = new JSONObject();
//                                bankDfObj.put("bankAccountID",bankAccountLogID);
//                                url ="https://mposapi.bjmymf.com/api/Pay/GetBankAccountByDFPayOrderId";
//                                String bankDfResponse = HttpUtils.sendJsonMessage(url, headerMap, bankDfObj.toJSONString());
//                                JSONObject bankDfRes = JSONObject.parseObject(bankDfResponse);
//                                logger.info("############################订单到账情况:{}",bankDfRes);
//
//                                if(bankDfRes.getIntValue("status")==1 && bankDfResponse.contains("银行处理成功")){
//                                    logger.info("订单:{},金额：{}已成功到账！！！",orderInfo.getId(),orderInfo.getRealMoney());
//                                }else{
//                                    logger.info("***********************订单:{},金额：{}未到账！修改收款号不可用",orderInfo.getId(),orderInfo.getRealMoney());
//                                    userRecipientInfo.setAvailable(0);
//                                    userRecipientInfo.setChannelDisabled(1);
//                                    userRecipientInfo.setDisabledInfo("订单:"+orderInfo.getId()+",金额："+MoneyUtil.fenToYuan(orderInfo.getRealMoney()+"")+"未到账！!!");
//                                    userRecipientService.updateById(userRecipientInfo);
//                                }

                                break;
                            }
                        }
                    }
                }
            }else {
                loginService.eftlogin(userRecipientInfo);
            }
        }
    }



    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
